﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace AutoCadConvert
{
    public class ModelFactory
    {
        protected List<string> settings = new List<string>();//导出对象名称
        protected Dictionary<string, string> appConfig = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);//模型到对象的名称映射

        public List<BspObject> cacheData = new List<BspObject>();
        public List<string> Setting { get { return settings; }}
        public Dictionary<string, string> Dict{ get { return appConfig; }}

        public int IndexOf(Type value)
        {//索引
            return settings.IndexOf(value.Name);
        }
        public ModelFactory()
        {
            try
            {
                foreach (SettingsProperty item in Properties.Settings.Default.Properties)
                {
                    if (item.PropertyType.FullName == "System.Collections.Specialized.StringCollection")
                    {//查找配置文件的节点
                        StringCollection children = Properties.Settings.Default[item.Name] as StringCollection;
                        if (item.Name== "标签")
                            settings.AddRange(children.Cast<string>());
                        else if(children!=null)
                            foreach (string child in children)
                                if (!appConfig.ContainsKey(item.Name))
                                    appConfig.Add(item.Name, child);
                                else
                                    appConfig[item.Name] += "," + child;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public Type GetBspObjectType(string szType)
        {
            return Assembly.GetExecutingAssembly().GetType("AutoCadConvert." + szType, false, true);
        }
        public BspObject CreateBspObject(Type type)
        {
            var query = cacheData.Where(o => o.GetType() == type);
            if (query.Count() > 0)
                return query.First();
            else
                return Assembly.GetExecutingAssembly().CreateInstance(type.FullName, true, BindingFlags.Default, null, new object[] { }, null, null) as BspObject;
        }
        public BspObject CreateBspObject(Type type, object entity)
        {
            var query = cacheData.Where(o => o.GetType() == type);
            if (query.Count() > 0)
                return query.First();
            else
                return Assembly.GetExecutingAssembly().CreateInstance(type.FullName, true, BindingFlags.Default, null, new object[] {entity}, null, null) as BspObject;
        }
    }
}
